<?php
class AudiencelistsController extends AppController {
	var $name = 'Audiencelists';
	
	var $uses = array('User', 'Survey', 'Audiencelist');
	
	/**
	 * Display all non deleted audience lists for the given user
	 * 
	 * @param object $user_id [optional]
	 * @return 
	 */
	function index($user_id=null){
		// Grab the user to which this survey belongs
		$active_user = $this->Auth->user();
		
		$users_audiencelists = $this->Audiencelist->find('all', 
				array('fields' => array('id', 'name', 'is_deleted'), 
				'conditions' => array('Audiencelist.user_id'=>$active_user['User']['id'], 'Audiencelist.is_deleted' => 0)));
						
		$this->set('audiencelists', $users_audiencelists);	
	}
	
	/**
	 * Adds a new Audience List to the database
	 * @return 
	 */
	function add(){
		if(empty($this->data)) return;
		
		$active_user = $this->Auth->user();
		$this->data['Audiencelist']['user_id'] = $active_user['User']['id'];
		
		$this->Audiencelist->set($this->data);
		
		if($this->Audiencelist->validates()){
			$this->Audiencelist->save($this->data);
			
			// View the new audience list
			$this->redirect(array('action' => 'view/'.$this->Audiencelist->id));
		}
	}
	
	/**
	 * Views information for a given
	 * audience list, displaying search results
	 * if needed and editing if requested
	 * @return 
	 * @param object $audiencelist_id The Id of the Audience List being viewed / edited
	 */
	function view($audiencelist_id = null) {
		if(! $this->_doesAudiencelistBelongToAuthedUser($audiencelist_id)){
			$this->redirect(array('action' => 'index'));
			return;
		}
		
		$defaultSearchName = 'Enter a name for which to search';
		
		$this->set('display', false);
		
		//Initialize search variables
		$searchUsername = "";
		$searchFirstname = "";
		$searchLastname = "";
		$searchEmail = "";
		
		
		$this->Audiencelist->id = $audiencelist_id;
		$this->Audiencelist->read();
		
		$this->set('id', $audiencelist_id);
		
		$this->Audiencelist->id = $audiencelist_id;
		$this_audiencelist = $this->Audiencelist->read();
		$this->set('this_audiencelist', $this_audiencelist);
		
		$this->User->bindModel(array('hasOne'=>array('AudiencelistsUsers')));
		$users = $this->User->find('all', array(
			'fields' => array('User.username', 'User.firstname', 'User.lastname'),
			'conditions'=>array('AudiencelistsUsers.audiencelist_id'=>$audiencelist_id)
		));
		
		$this->set('users', $users);
		
		if(!empty($this->data)){
			$searchUsername = trim($this->data['User']['username']);
			$searchFirstname = trim($this->data['User']['firstname']);
			$searchLastname = trim($this->data['User']['lastname']);
			$searchEmail = trim($this->data['User']['email']);
		
			$filters = array();
			$conditions = array();
			
			// Filter by username
			 if(!empty($searchUsername)) {
		    	//Set up the search filters
		        $filters = array('User.username LIKE' => '%'.low($searchUsername).'%');
		    }
			
			// Filter by first name
			if(!empty($searchFirstname)) {
		    	//Set up the search filters
				$key = 'User.firstname LIKE';
				$value = '%'.$searchFirstname.'%';
				$firstnameFilters = array($key=>$value);
				$filters = array_merge($filters, $firstnameFilters);
		    }
			
			// filter by last name
			if(!empty($searchLastname)) {
		    	//Set up the search filters
				$key = 'User.lastname LIKE';
				$value = $searchLastname;
				$lastnameFilters = array($key=>$value);
				$filters = array_merge($filters, $lastnameFilters);
		    }
			
			// Filter by e-mail
			if(!empty($searchEmail)) {
				$key = 'User.email LIKE';
				$value = $searchEmail;
				$emailFilters = array($key=>$value);
				$filters = array_merge($filters, $emailFilters);
			}
			
			//Merge the search conditions with those passed as a parameter
			$conditions = array_merge($conditions, $filters);
		
			//Get the paginated results
			$this->paginate['User'] = compact('conditions', 'fields', 'order', 'contain', 'limit', 'group');
			$users = $this->paginate('User');

			$this->set('searchResults', $users);
			$this->set('display', true);
		
		}
		
		$this->set('searchUsername', $searchUsername);
		$this->set('searchFirstname', $searchFirstname);
		$this->set('searchLastname', $searchLastname);
		$this->set('searchEmail', $searchEmail);
		
		if(isset($this->data['Audiencelist']['searchName'])){
			$searchName = $this->data['Audiencelist']['searchName'];
		}
	}
	
	/**
	 * Sets the "is_deleted" flag of the database entry to 1
	 * @return 
	 * @param object $audiencelist_id The Audience List to be deleted
	 */
	
	function delete($audiencelist_id){
		if(! $this->_doesAudiencelistBelongToAuthedUser($audiencelist_id)){
			$this->redirect(array('action' => 'index'));
			return;
		}
		
		$this->data['Audiencelist']['id'] = $audiencelist_id;
		$this->data['Audiencelist']['is_deleted'] = 1;
		$this->Audiencelist->save($this->data);
		
		$this->redirect(array('action' => 'index'));
	}
	
	/**
	 * Adds a user to the specified Audience List
	 * @return nothing
	 * @param object $user_id The Id of the user to be added to the audience list
	 * @param object $audiencelist_id The Id of the audience list to which the User is to be added
	 */
	function addUserToAudiencelist($user_id, $audiencelist_id){
		if(! $this->_doesAudiencelistBelongToAuthedUser($audiencelist_id)){
			$this->redirect(array('action' => 'index'));
			return;
		}
		
		$this->Survey->bindModel(array('hasOne'=>array('AudiencelistsSurveys')));
		$surveys = $this->Survey->find('all', array(
			'fields' => array('Survey.id', 'Survey.name',),
			'conditions'=>array('AudiencelistsSurveys.audiencelist_id'=>$audiencelist_id)
		));
		foreach( $surveys as $survey ){
			// register the user for the survey
			$this->User->habtmAdd('Survey', $user_id, $survey['Survey']['id']);
		}
		
		// Add the user to the audiencelist
		$this->User->habtmAdd('Audiencelist', $user_id, $audiencelist_id);
		
		$this->redirect(array('action' =>'view', 'id'=>$audiencelist_id));
	}
	
	function _doesAudiencelistBelongToAuthedUser($audiencelist_id){
		$active_user = $this->Auth->user();
		
		$this->Audiencelist->bindModel(array('hasOne' => array('AudiencelistsUsers')));
		$habtmEntry =	$this->Audiencelist->find('all', array(
				'conditions'=>array(
				'AudiencelistsUsers.audiencelist_id'=>$audiencelist_id, 
				'AudiencelistsUsers.user_id'=>$active_user['User']['id'],
				),
		));
		
		if(empty($habtmEntry)){
			$this->Session->setFlash('There was an error processing your request. Please try again');
			return false;
		}
		else return true;
	}
}
?>